package com.example.emos.wx.mapper;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import com.example.emos.wx.entity.MessageEntity;
import com.example.emos.wx.entity.MessageRefEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @ClasName MessageDao
 * @Author leikw
 * @Date 2023/2/7 15:07
 * @Version V1.0
 */
@Repository
public class MessageDao {


    @Autowired
    private MongoTemplate mongoTemplate;


    /**
     * @Author leikw
     * @Description 增加消息主体
     * @Date  2023/2/7 15:09
     */
    public String insert(MessageEntity entity){
        Date sendTime=entity.getSendTime();
        sendTime= DateUtil.offset(sendTime, DateField.HOUR,8);
        entity.setSendTime(sendTime);
        entity=mongoTemplate.save(entity);
        return entity.get_id();
    }

    /**
     * @Author leikw
     * @Description 根据id查询消息
     * @Date  2023/2/7 15:11
     */
    public HashMap searchMessageById(String id){
        HashMap map=mongoTemplate.findById(id,HashMap.class,"message");
        Date sendTime= (Date) map.get("sendTime");
        sendTime=DateUtil.offset(sendTime,DateField.HOUR,-8);
        map.replace("sendTime",DateUtil.format(sendTime,"yyyy-MM-dd HH:mm"));
        return map;
    }

    /**
     * @Author leikw
     * @Description 根据用户查看自己可接收的消息
     * @Date  2023/2/7 15:13
     */
    public List<HashMap> searchMessageByPage(int userId, long start, int length){
        //构造MongoDB查询条件
        JSONObject json=new JSONObject();
        json.set("$toString","$_id");
        Aggregation aggregation=Aggregation.newAggregation(
                Aggregation.addFields().addField("id").withValue(json).build(),
                Aggregation.lookup("message_ref","id","messageId","ref"),
                Aggregation.match(Criteria.where("ref.receiverId").is(userId)),
                Aggregation.sort(Sort.by(Sort.Direction.DESC,"sendTime")),
                Aggregation.skip(start),
                Aggregation.limit(length)
        );

        //查询并遍历组装消息数据
        AggregationResults<HashMap> results=mongoTemplate.aggregate(aggregation,"message",HashMap.class);
        List<HashMap> list=results.getMappedResults();
        list.forEach(one->{
            //取出消息 对应 接收对象信息
            List<MessageRefEntity> refList= (List<MessageRefEntity>) one.get("ref");
            MessageRefEntity entity=refList.get(0);

            boolean readFlag=entity.getReadFlag();
            String refId=entity.get_id();

            //构造消息
            one.put("readFlag",readFlag);
            one.put("refId",refId);
            one.remove("ref");
            one.remove("_id");
            Date sendTime= (Date) one.get("sendTime");
            sendTime=DateUtil.offset(sendTime,DateField.HOUR,-8);

            //如果数据是今天发送的显示小时 不是则显示日期
            String today=DateUtil.today();
            if(today.equals(DateUtil.date(sendTime).toDateStr())){
                one.put("sendTime",DateUtil.format(sendTime,"HH:mm"));
            }
            else{
                one.put("sendTime",DateUtil.format(sendTime,"yyyy/MM/dd"));
            }
        });
        return list;
    }



}
